/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.app.imageupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * The Class LocalServerImageUploadMethod.
 *
 * @author Xi Wei
 */
public class LocalServerImageUploadMethod implements ImageUploadMethod {

	/** The log. */
	protected Logger log = LoggerFactory.getLogger(getClass());

	/* (non-Javadoc)
	 * @see com.xw.app.imageupload.ImageUploadMethod#uploadImage(javax.servlet.http.HttpServletRequest, org.springframework.web.multipart.MultipartFile, java.lang.String, java.lang.String)
	 */
	@Override
	public String uploadImage(HttpServletRequest request, MultipartFile file, String relativePath, String fileName) {
		String path = request.getSession().getServletContext().getRealPath(relativePath);
		log.info("Real Path = " + path);
		File pathFile = new File(path);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}

		try {
			file.transferTo(new File(path + "/" + fileName));

			String ip = "http://" + request.getServerName();
			if (request.getServerPort() != 80) {
				ip += ":" + request.getServerPort();
			}
			String accessUrl = ip + request.getContextPath() + "/" + relativePath + "/" + fileName;
			return accessUrl;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/* (non-Javadoc)
	 * @see com.xw.app.imageupload.ImageUploadMethod#uploadImage(javax.servlet.http.HttpServletRequest, java.io.InputStream, java.lang.String, java.lang.String)
	 */
	@Override
	public String uploadImage(HttpServletRequest request, InputStream is, String relativePath, String fileName) {
		String path = request.getSession().getServletContext().getRealPath(relativePath);
		log.info("Real Path = " + path);
		File pathFile = new File(path);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}

		try {
			
			FileCopyUtils.copy(is, new FileOutputStream(new File(path + "/" + fileName)));

			String ip = "http://" + request.getServerName();
			if (request.getServerPort() != 80) {
				ip += ":" + request.getServerPort();
			}
			String accessUrl = ip + request.getContextPath() + "/" + relativePath + "/" + fileName;
			return accessUrl;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
